use crate::utils::encrypt_util::{get_salt_md5, get_signature};
use crate::utils::http_util::handle_http;
use crate::utils::service_config::ServiceConfig;
use crate::utils::user_info::set_user_info;
use log::{error, info};
use reqwest::Response;
use serde_json::{json, Value};
use std::time::Duration;
use tokio::runtime::Runtime;

pub fn login(
    login_type: String,
    account: Option<String>,
    password: Option<String>,
    phone: Option<String>,
    captcha: Option<String>,
) {
    if login_type == "phone" {
        handle_login(login_type, phone.unwrap(), captcha.unwrap())
    } else {
        handle_login(login_type, account.unwrap(), password.unwrap())
    }
}

fn handle_login(login_type: String, account: String, password: String) {
    let rt = Runtime::new().expect("创建tokio运行时失败");
    let mut post_json = get_signature();
    if login_type == "phone" {
        post_json["type"] = json!(1);
        post_json["phone"] = json!(account);
        post_json["loginCode"] = json!(password);
    }
    if login_type == "username" {
        post_json["type"] = json!(2);
        post_json["account"] = json!(account);
        post_json["password"] = json!(get_salt_md5(&password));
    }
    rt.block_on(async {
        let client = reqwest::Client::new();
        let service_config = ServiceConfig::new();
        let url = service_config.get_maview_url("login");
        let response = client
            .post(url)
            .timeout(Duration::from_secs(5))
            .json(&post_json)
            .send()
            .await
            .unwrap();
        if response.status().is_success() {
            let response_json: Value = response.json().await.unwrap();
            if response_json["code"] == 0 {
                let mut user_info = json!(
                    {
                        "login_type": login_type,
                        "token": response_json["data"]["token"],
                        "nickname": response_json["data"]["nickname"],
                        "account": response_json["data"]["account"],
                        "uid": response_json["data"]["uid"],
                        "user_phone": response_json["data"]["user_phone"],
                        "create_time": response_json["data"]["createTime"],
                    }
                );
                if login_type == "username" {
                    user_info["username"] = json!(account);
                    user_info["check"] = json!(password);
                }
                match set_user_info(user_info) {
                    Ok(_) => info!("登录成功"),
                    Err(e) => error!("{}", e),
                }
            } else {
                error!("{}", response_json["msg"])
            }
        } else {
            error!("获取验证码失败")
        }
    });
}
